package com.dhcc.controller;

import com.dhcc.api.R;
import com.dhcc.core.ObsService;
import com.dhcc.dto.FileUrlDto;
import com.dhcc.utils.FileUtil;
import jakarta.annotation.Resource;
import lombok.AllArgsConstructor;
import org.apache.commons.compress.utils.IOUtils;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.http.MediaType;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * 文件上传下载控制器
 *
 * @Author: 翟睿萌
 * @Description:
 */
@RestController
@AllArgsConstructor
@RequestMapping("/userSystem/file")
public class FileController {
    @Resource
    private ObsService fileStorageService;
    @Resource
    private Environment environment;
    /**
     * 上传(返回带地址的url)
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/uploadUrl")
    public R uploadUrl(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        InputStream inputStream = file.getInputStream();
        String contentType = null;
        if (originalFilename != null) {
            contentType = getFileType(originalFilename);
        }
        String filePath = fileStorageService.store("fj_", originalFilename, contentType, inputStream);
        String property = environment.getProperty("minio.url" )+ "/";
        filePath=property+filePath;
        return R.data(filePath);
    }
    /**
     * 下载
     */
    @PostMapping("/download")
    public ResponseEntity<byte[]> download(@RequestBody FileUrlDto fileUrlDto) throws IOException {
        String property = environment.getProperty("minio.url" )+ "/";
        String downloadUrl=null;
        if (fileUrlDto.getUrl().startsWith("http://")||fileUrlDto.getUrl().startsWith("https://")){
            downloadUrl = fileUrlDto.getUrl();
        }else {
            downloadUrl=property+fileUrlDto.getUrl();
        }
        int index = downloadUrl.lastIndexOf("/");
        String fileName = downloadUrl.substring(index+1);
        String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString());
        InputStream inputStream = fileStorageService.downloadFile(downloadUrl);
        String fileType = getFileType(fileName);
        byte[] bytes = IOUtils.toByteArray(inputStream);
        if (bytes.length == 0) {
            // 文件不存在，返回错误信息
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(null);
        }
        // 设置 HTTP 头信息，告诉浏览器如何处理下载文件
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + encodedFileName + "\"");

        // 创建 ResponseEntity 对象并返回文件资源
        String substring = fileName.substring(fileName.lastIndexOf('.') + 1);
        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(bytes.length)
                .contentType(getContentType(substring))
                .body(bytes);
    }
    /**
     * 删除
     */
    @PostMapping("/delete")
    @Transactional
    public R<Boolean> delete( @RequestBody FileUrlDto fileUrlDto) {
        String property = environment.getProperty("minio.url" )+"/";
        String filePath = null;
        if (fileUrlDto.getUrl().startsWith("http://")||fileUrlDto.getUrl().startsWith("https://")){
            filePath = fileUrlDto.getUrl();
        }else {
            filePath=property+fileUrlDto.getUrl();
        }
        boolean delete = fileStorageService.delete(filePath);
        return R.status(delete);
    }
    /**
     * 获取文件类型
     * @param fileName
     * @return
     */

    private static String getFileType(String fileName) {
        // 获取文件后缀
        int dotIndex = fileName.lastIndexOf(".");
        if (dotIndex == -1) {
            // 没有后缀，无法确定文件类型
            return null;
        }
        String extension = fileName.substring(dotIndex + 1).toLowerCase();
        // 查找文件类型映射
        return FileUtil.getFileType(extension);
    }

    /**
     * 根据文件拓展名获取对应的 MediaType
     * @param fileExtension
     * @return MediaType 对象，如果没有匹配的文件类型则返回默认的二进制流类型
     */
    private MediaType getContentType(String fileExtension) {
        if (fileExtension != null) {
            switch (fileExtension.toLowerCase()) {
                case "png":
                    return MediaType.IMAGE_PNG;
                case "jpg":
                case "jpeg":
                    return MediaType.IMAGE_JPEG;
                case "pdf":
                    return MediaType.APPLICATION_PDF;
                case "txt":
                    return MediaType.TEXT_PLAIN;
                // 添加更多文件类型的判断和对应的 MediaType
                default:
                    break;
            }
        }
        // 默认返回二进制流类型
        return MediaType.APPLICATION_OCTET_STREAM;
    }
}
